package com.changgou.weixin.service;


import com.changgou.entity.HttpClient;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：zhangchen
 * @date ：Created in 2020/1/15
 * @description ：
 * @version: 1.0
 */
@Service
public class PayServiceImpl implements PayService {

    @Value("${weixin.appid}")
    private String appid;

    @Value("${weixin.partner}")
    private String partner;

    @Value("${weixin.partnerkey}")
    private String partnerkey;

    @Value("${weixin.notifyurl}")
    private String notifyurl;

    @Override
    public Map<String, String> createNativePay(Map<String, String> paramsMap) {

        try {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("appid", appid);
            paramMap.put("mch_id",partner );
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            paramMap.put("body", "畅购商城商品销售");
            //订单号
            paramMap.put("out_trade_no", paramsMap.get("outtradeno"));
            paramMap.put("total_fee", paramsMap.get("totalfee"));
            paramMap.put("spbill_create_ip", "127.0.0.1");
            paramMap.put("notify_url", notifyurl);
            paramMap.put("trade_type", "NATIVE");
            // paramMap.put("sign", "");

            //map转成xml字符串，可以携带签名
            String xml = WXPayUtil.generateSignedXml(paramMap, partnerkey);

            String url = WXPayConstants.UNIFIEDORDER_URL;

            HttpClient httpClient = new HttpClient(url);
            httpClient.setHttps(true);
            httpClient.setXmlParam(xml);

            httpClient.post();

            String content = httpClient.getContent();

            Map<String, String> resultMap = WXPayUtil.xmlToMap(content);

            return resultMap;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Map queryPayStatus(String orderId) {
        try {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("appid", appid);
            paramMap.put("mch_id",partner );
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            //订单号
            paramMap.put("out_trade_no", orderId);
            // paramMap.put("sign", "");

            //map转成xml字符串，可以携带签名
            String xml = WXPayUtil.generateSignedXml(paramMap, partnerkey);

            String url = WXPayConstants.ORDERQUERY_URL;

            HttpClient httpClient = new HttpClient(url);
            httpClient.setHttps(true);
            httpClient.setXmlParam(xml);

            httpClient.post();

            String content = httpClient.getContent();

            Map<String, String> resultMap = WXPayUtil.xmlToMap(content);

            return resultMap;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成支付二维码
     * @param response 响应
     * @param contents url链接
     * @throws Exception
     */
    public static void writerPayImage(HttpServletResponse response, String contents) throws Exception{
        ServletOutputStream out = response.getOutputStream();
        try {
            Map<EncodeHintType,Object> hints = new HashMap<EncodeHintType,Object>();
            hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
            hints.put(EncodeHintType.MARGIN, 0);
            BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE,300,300,hints);
            MatrixToImageWriter.writeToStream(bitMatrix,"jpg",out);
        }catch (Exception e){
            throw new Exception("生成二维码失败！");
        }finally {
            if(out != null){
                out.flush();
                out.close();
            }
        }
    }
}
